/**
 * 初始化默认值 (解决el-elect的persistent为false初始化值显示不正确的问题)
 */
export function useSelectDefaultLabel(
  multiple: boolean,
  labelKey: string | undefined,
  valueKey: string | undefined,
  list: unknown[],
  selectData: any,
  elSelectRef: $RefComp<'ElSelect'>
) {
  if (elSelectRef.value) {
    // 防止初始化值显示不正确
    if (!multiple && labelKey && valueKey && selectData !== '') {
      if (typeof selectData === 'object' && !Array.isArray(selectData)) {
        elSelectRef.value.states.selectedLabel = String(selectData[labelKey]);
      } else if (Array.isArray(list)) {
        // 有labelKey值则list一定是对象数组
        const select = (list as Record<string, unknown>[]).find((item: Record<string, unknown>) => item[valueKey] === selectData) as
          | Record<string, number | string>
          | undefined;
        select && (elSelectRef.value.states.selectedLabel = String(select[labelKey]));
      }
    } else if (multiple && labelKey && valueKey && Array.isArray(selectData) && selectData.length > 0) {
      if (typeof selectData[0] === 'object') {
        const obj: Record<string, Record<string, unknown>> = {};
        selectData.forEach((item: Record<string, unknown>) => {
          const key = (valueKey in item ? item[valueKey] : undefined) as number | string | undefined;
          key && (obj[key] = item);
        });

        elSelectRef.value.states.selected.forEach((item: Record<string, number | string>) => {
          const _val = (item.value ?? '') as string;

          if (_val in obj) {
            item.currentLabel = String(obj[_val]![labelKey] || '');
            item.value = (obj[_val]![valueKey] ?? '') as number | string;
          }
        });
      } else if (Array.isArray(list)) {
        if (Array.isArray(elSelectRef.value.states.selected)) {
          const obj: Record<string, Record<string, unknown>> = {};
          list.forEach((item) => {
            const newItem = item as Record<string, unknown>;
            const key = (valueKey in newItem ? newItem[valueKey] : undefined) as number | string;
            key && (obj[key] = newItem);
          });
          elSelectRef.value.states.selected.forEach((item: Record<string, number | string>) => {
            const _val = (item.value ?? '') as string;
            if (_val in obj) {
              item.currentLabel = String(obj[_val]![labelKey] || '');
              item.value = (obj[_val]![valueKey] ?? '') as number | string;
            }
          });
        }
      }
    }
  }
}
